package com.zj;

import org.apache.log4j.Logger;

import java.io.*;
import java.lang.reflect.Type;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Teacher {
    public static void main(String[] args) {
        String host="localhost";
        int port=12000;
        //创建一个socket对象
        Scanner keyword=new Scanner(System.in);
        boolean flag=true;
        try(
                //创建一个socket对象
                Socket s=new Socket(host,port);
                //利用套接字获取字节流并转换成字符流
                PrintWriter pw=new PrintWriter(s.getOutputStream());//println可以一行一行的发送
                //利用套接字获取字节流并转换成字符流
//                Scanner sc=new Scanner(s.getInputStream());//读取服务器的响应 nextLine()
                InputStream sc = s.getInputStream()
        ){
            System.out.println("教师端已经与学生端"+s.getRemoteSocketAddress()+"连接成功");
            do{
                System.out.println("====教师端操作指南===");
                System.out.println("1.学生端截图 screenshot");
                System.out.println("2.学生端关机 shutdown");
                System.out.println("3.发送信息 sendMessage");
                System.out.println("4.退出");
                System.out.println("5.错误命令");
                System.out.println("=======================");
                System.out.println("请输入您的选择：");
                String command=keyword.nextLine();  //输入操作选项
                String response=null;
                if ("1".equalsIgnoreCase(command)) {
                    pw.println("screenshot");
                    pw.flush();

                    // 改用原始InputStream
                    InputStream rawInput = s.getInputStream();

                    // 1. 读取协议头（10字节）
                    byte[] header = new byte[10];
                    rawInput.readNBytes(header, 0, 10);
                    String headerStr = new String(header, StandardCharsets.UTF_8);
                    System.out.println("调试：收到协议头[" + headerStr + "]");

                    if ("SCREENSHOT".equals(headerStr)) {
                        // 2. 读取文件大小（8字节）
                        byte[] sizeBytes = new byte[8];
                        rawInput.readNBytes(sizeBytes, 0, 8);
                        long fileSize = ByteBuffer.wrap(sizeBytes).getLong();
                        System.out.println("调试：文件大小=" + fileSize + "字节");

                        // 3. 读取图片数据
                        File outputFile = new File("received_screenshot.png");
                        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                            byte[] buffer = new byte[4096];
                            long remaining = fileSize;
                            while (remaining > 0) {
                                int read = rawInput.read(buffer, 0, (int) Math.min(buffer.length, remaining));
                                if (read == -1) throw new IOException("未读完预期数据");
                                fos.write(buffer, 0, read);
                                remaining -= read;
                            }
                            System.out.println("截图已保存至 " + outputFile.getAbsolutePath());
                        }
                    } else {
                        System.out.println("协议头不匹配，丢弃数据");
                        rawInput.skip(rawInput.available()); // 清空缓冲区
                    }
                }else if("2".equalsIgnoreCase(command)){
                    pw.println("shutdown");
                }else if("3".equalsIgnoreCase(command)){
                    System.out.println("请输入要发送的信息：");
                    String message=keyword.nextLine();
                    pw.println("sendMessage "+message);
                }else if("5".equalsIgnoreCase(command)){
                    pw.println("abcdef");
                }else {
                    pw.println("QUIT");
                    pw.flush();
                    flag=false;
                    break;
                }
                pw.flush();
                // 检查输入流中是否还有数据
                if (sc.available()>0) {
                    //取服务器的响应
                    response = sc.toString();
                    System.out.println("服务器的响应：" + response);
                } else {
                    System.out.println("服务器已关闭连接或无响应。");
                    flag = false;
                }
            }while(flag);
            System.out.println("教师端退出登录");
        }catch (Exception e){
            // 建议使用日志记录异常
            Logger log = Logger.getLogger(Teacher.class.getName());
            log.error("发生异常", e);
        }
    }
}